from scipy import stats
import math
from data import bridge
from damage import damage
import matplotlib.pyplot as plt
import numpy as np
import csv
import json
import os

def analysis(bridgeType, damageName,):
    
    # 判断输入的正确性
    # typeKeys = list(bridge.keys())
    # if bridgeType not in typeKeys:
        # print('输入格式有误')

    # 获取桥梁易损性函数中位值
    slightMedian = bridge[bridgeType]['slight']
    moderateMedian = bridge[bridgeType]['moderate']
    extensiveMedian = bridge[bridgeType]['extensive']
    completeMedian = bridge[bridgeType]['complete']

    # 获取灾害强度相关信息
    PGA = damage[damageName]['PGA']

    # 识别文件路径
    resultPath = os.path.dirname(__file__)

    # 绘制易损性曲线
    # 确定坐标轴
    plt.xlim((0,2))
    plt.ylim((0,1))

    plt.title("Fragility of Bridge") 
    plt.xlabel("PGA(g)") 
    plt.ylabel("Exceeding Probability")

    # slight
    x1 = np.linspace(0.01,2,200)
    y1 = []
    for i in x1:
        k = stats.norm.cdf((math.log(i) - math.log(slightMedian))/(0.6))
        y1.append(k)

    plt.plot(x1,y1,c='r',linewidth=1,linestyle='-',label='slight')

    # moderate
    x2 = np.linspace(0.01,2,200)
    y2 = []
    for i in x2:
        k = stats.norm.cdf((math.log(i) - math.log(moderateMedian))/(0.6))
        y2.append(k)

    plt.plot(x2,y2,c='g',linewidth=1,linestyle=':',label='moderate')

    # extensive
    x3 = np.linspace(0.01,2,200)
    y3 = []
    for i in x3:
        k = stats.norm.cdf((math.log(i) - math.log(extensiveMedian))/(0.6))
        y3.append(k)

    plt.plot(x3,y3,c='b',linewidth=1,linestyle='--',label='extensive')

    # complete
    x4 = np.linspace(0.01,2,200)
    y4 = []
    for i in x4:
        k = stats.norm.cdf((math.log(i) - math.log(completeMedian))/(0.6))
        y4.append(k)

    plt.plot(x4,y4,c='m',linewidth=1,linestyle='-.',label='complete')

    # 图例和绘制
    plt.legend(['slight','moderate','extensive','complete'],loc = 'lower right')
    plt.savefig(resultPath + r'fragility.jpg')
    plt.show()

    # 计算超越概率
    exceedingProbability = []
    exceedingProbability.append(stats.norm.cdf((math.log(PGA) - math.log(slightMedian))/(0.6)))
    exceedingProbability.append(stats.norm.cdf((math.log(PGA) - math.log(moderateMedian))/(0.6)))
    exceedingProbability.append(stats.norm.cdf((math.log(PGA) - math.log(extensiveMedian))/(0.6)))
    exceedingProbability.append(stats.norm.cdf((math.log(PGA) - math.log(completeMedian))/(0.6)))


    # 计算处于五种破坏状态的概率
    damageState = [0]*5
    damageState[0] = exceedingProbability[3]
    damageState[1] = exceedingProbability[2] - exceedingProbability[3]
    damageState[2] = exceedingProbability[1] - exceedingProbability[2]
    damageState[3] = exceedingProbability[0] - exceedingProbability[1]
    damageState[4] = 1 - exceedingProbability[0]


    # 将结果转换成csv文件
    # 创建csv文件
    with open(resultPath + r'\bridgeresult.csv', 'w', newline='', encoding='utf-8') as f:
        # 构建写入对象
        writer = csv.writer(f)
        
        # 列名
        head = ['name', 'none', 'slight', 'moderate', 'extensive','complete']
        result = [bridgeType, damageState[4], damageState[3], damageState[2], damageState[1], damageState[0]]
        
        # 写入数据
        writer.writerow(head)
        writer.writerow(result)

    # 将结果转换成json文件
    # 创建结果信息的字典
    resultDic = {}.fromkeys(head)

    resultDic['name'] = bridgeType
    resultDic['none'] = damageState[4]
    resultDic['slight'] = damageState[3]
    resultDic['moderate'] = damageState[2]
    resultDic['extensive'] = damageState[1]
    resultDic['complete'] = damageState[0]

    with open(resultPath + r'\bridgeresult.json', 'w') as g:
        json.dump(resultDic, g, indent=4, ensure_ascii=False)

    return print('OK!')
